package collect

import (
	"compress/gzip"
	"fmt"
	"io"
	"os"
	"strings"
)

const openFileOptions int = os.O_CREATE | os.O_RDWR
const openFilePermissions os.FileMode = 0660

var numMonth = map[string]string{
	"Jan":  "01",
	"Feb":  "02",
	"Mar":  "03",
	"Apr":  "04",
	"May":  "05",
	"June": "06",
	"July": "07",
	"Aug":  "08",
	"Sept": "09",
	"Oct":  "10",
	"Nov":  "11",
	"Dec":  "12",
}

func NginxTimeFormat(t string) string {
	mainTime := strings.Split(t, " ")[0]

	timeSplit := strings.Split(mainTime, ":")

	daySplit := strings.Split(timeSplit[0], "/")

	return daySplit[2] + "-" + numMonth[daySplit[1]] + "-" + daySplit[0] + " " + timeSplit[1] + ":" + timeSplit[2] + ":" + timeSplit[3]
}

func unZip(zipFile string) {
	handle, err := openFile(zipFile)
	if err != nil {
		fmt.Println("[ERROR] Opening file:", err)
	}
	defer closeFile(handle)

	zipReader, err := gzip.NewReader(handle)
	if err != nil {
		fmt.Println("[ERROR] New gzip reader:", err)
	}
	defer zipReader.Close()

	dest, _ := openFile(dstFile(zipFile))

	_, err = io.Copy(dest, zipReader)

	if err != nil {
		fmt.Println("[ERROR] New gzip reader:", err)
	}

}

func dstFile(zipFile string) string {
	fileSplit := strings.Split(zipFile, ".")
	fileSplit = fileSplit[:len(fileSplit)-1]

	dest := strings.Join(fileSplit, ".")
	return dest
}

func openFile(fileToOpen string) (*os.File, error) {
	return os.OpenFile(fileToOpen, openFileOptions, openFilePermissions)
}

func closeFile(handle *os.File) {
	if handle == nil {
		return
	}

	err := handle.Close()
	if err != nil {
		fmt.Println("[ERROR] Closing file:", err)
	}
}
